package com.xc.hotelmgr.datahandlermt.sdk;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.codec.binary.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.Random;

@Slf4j
public class MtClient {
    private static final String VERSION = "1.0";
    private static final Random random = new Random();

    private void setBaseParam(FxBaseApiRequest request) {
        request.setVersion(VERSION);
        request.setTimestamp(System.currentTimeMillis()/1000);
        request.setNonce(random.nextInt(Integer.MAX_VALUE));
        request.setSignature(calculateSignature(request));
    }

    private String calculateSignature(FxBaseApiRequest request){

        // 计算签名
        String rawSignStr = "accesskey=" + request.getAccesskey() + "&data=" + request.getData()
                + "&method=" + request.getMethod() + "&nonce=" + request.getNonce()
                + "&partnerId=" + request.getPartnerId() + "&timestamp=" + request.getTimestamp()
                + "&version=" + request.getVersion();
        return this.hmacSha1(rawSignStr, request.getSecretKey());
    }

    // hmacSha1加密
    private String hmacSha1(String plainText, String secretKey) {
        SecretKeySpec secretKeySpec = new SecretKeySpec(StringUtils.getBytesUtf8(secretKey), "HmacSHA1");
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(secretKeySpec);
            return Base64.encodeBase64String(mac.doFinal(StringUtils.getBytesUtf8(plainText)));
        } catch (GeneralSecurityException var5) {
            throw new IllegalArgumentException(var5);
        }
    }

    public String post(FxBaseApiRequest request) {
        setBaseParam(request);
        String bean2JSString = JSON.toJSONString(request);
        String host = "https://fenxiao.meituan.com/opdtor/api";
        try {
            return HttpRequest.post(host)
                    .header("Content-Type", "application/json; charset=utf-8")
                    .header("Accept", "application/json")
                    .body(bean2JSString)
                    .timeout(20000)
                    .execute()
                    .body();
        }catch (Exception e){
            log.error(e.toString());
            return  HttpRequest.post(host)
                    .header("Content-Type", "application/json; charset=utf-8")
                    .header("Accept", "application/json")
                    .body(bean2JSString)
                    .timeout(20000)
                    .execute()
                    .body();
        }

    }
}
